<?php

namespace App\Service\Activity;

use App\Constants\ErrorCode;
use App\Helpers\AliyunUtil;
use App\Helpers\RedisUtil;
use App\Model\Act\WishTree;
use App\Model\Act\WishTreeGift;
use App\Model\CoinLog;
use App\Model\Gift;
use App\Model\Service\ConsumeService;
use App\Model\UserCoin;
use App\Model\UserPackBag;
use App\Service\BaseService;

/**
 * 许愿树-开始许愿
 */
class WishTreeMakeService extends BaseService
{
    public function handle()
    {
        return $this->setError(ErrorCode::PARAMETER_ERROR, '许愿树活动暂时已下架，请期待其他活动～');
        $wishTimes = $this->request->input('wish_times', 1);
        $costCoin = WishTree::getCostCoin($wishTimes);
        if (!$costCoin) return $this->setError(ErrorCode::PARAMETER_ERROR, '提交参数有误');

        //加入同步锁
        if (RedisUtil::concurrentLock($key = "WishTreeMakeService_{$this->userId}", 3)) {
            log_user_result($this->userId, "makewish_proccessing");
            return $this->setError(ErrorCode::OP_TOO_MANY, '操作频繁，请稍后再试！');
        }

        $userCoin = UserCoin::getUserInfo($this->userId);
        if (!$userCoin || $userCoin['total_coin'] < $costCoin) {
            return $this->setError(ErrorCode::COIN_NOT_ENOUGH, '剩余金币不足', ['uid' => $this->userId]);
        }
        //金币支出
        $result = ConsumeService::makeWish($this->userId, $costCoin, $userCoin);
        if (!$result) {
            return $this->setError(ErrorCode::COST_COIN_ERR, '金币消耗异常');
        }
        //许愿
        $giftList = $this->makeWish($wishTimes, $userCoin);
        return [
            'result' => 1,
            'tip' => "向许愿树许愿一次\n获得许愿奖励",
            'list' => $giftList
        ];
    }

    /**
     * 许愿
     */
    function makeWish($wishTimes = 1, $userCoin = [])
    {
        //获取许愿礼物
        $giftIds = WishTreeGift::getGiftIds($wishTimes);
        $giftItems = Gift::getBatchInfo(array_keys($giftIds));
        $list = [];
        foreach ($giftItems as $giftItem) {
            $giftNum = $giftIds[$giftItem['id']];
            $giftCoin = intval($giftItem['coin']) * $giftNum;
            $list[] = [
                'gift_name' => $giftItem['name'],
                'coin' => (string)$giftCoin,
                'num' => $giftNum,
                'gift_icon' => AliyunUtil::imageResize(AliyunUtil::IMG_HOST_V2 . $giftItem['icon'], 120, 120),
            ];

            //许愿记录入库
            WishTree::addRecord($this->userId, $giftItem['id'], $giftNum, $giftCoin);

            //背包礼物入库
            switch ($giftItem['type']) {
                case Gift::TYPE_PACKBAG:
                    UserPackBag::addRecord($this->userId, $giftItem['id'], $giftNum);
                    break;
                case Gift::TYPE_COIN:
                    ConsumeService::gainRechargeIncome($this->userId, $giftCoin, CoinLog::FROM_ACT_MAKE_WISH_COIN_IN);
                    break;
            }
        }
        return $list;
    }
}
